package me.youline.dataServer.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import me.youline.dataServer.entity.OfficialUserRecord;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

@Component
public class OfficialUserRecordDAO {
	
	@Autowired
	private JdbcTemplate template;
	
	private static final String TABLE_NAME = "yline_base_official_user";
	
	private static final String INSERT_SQL = "insert into "+TABLE_NAME + "(userId,isFollowed) values(?,?)";
	
	private static final String LOAD_SQL =" select * from "+TABLE_NAME;
	
	private static final String IS_OFFICAL_USER = " select count(1) from "+TABLE_NAME +" where userId = ? ";
	
	private static final String FOLLOWED_OFFICIAL_USER_QUERY = " select userId from "+TABLE_NAME+" where isFollowed = ? ";
	
	private RowMapper<OfficialUserRecord> ROW_MAPPER = new RowMapper<OfficialUserRecord>(){
		
		@Override
		public OfficialUserRecord mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			OfficialUserRecord r = new OfficialUserRecord();
			r.setFollowed(rs.getBoolean("isFollowed"));
			r.setUserId(rs.getLong("userId"));
			r.setId(rs.getLong("id"));
			return r;
		}
	};
	
	/**
	 * 加载所有官方号用户ID
	 * @return
	 */
	public List<OfficialUserRecord> loadOfficalUserIds(){
		return template.query(LOAD_SQL, ROW_MAPPER);
	}
	
	
	/**
	 * 将指定用户设置为官方号
	 * @param r
	 */
	public void addOfficalUserId(OfficialUserRecord r){
		template.update(INSERT_SQL,new Object[]{r.getUserId(),r.isFollowed()});
	}
	
	/**
	 * 判断当前用户是否为官方号
	 * @param userId
	 * @return
	 */
	public boolean isOfficalUser(Long userId){
		Integer r = template.queryForObject(IS_OFFICAL_USER, new Object[]{userId},Integer.class);
		return r > 0;
	}
	
	
	/**
	 * 加载需要用户默认关注的官方号列表
	 * @return
	 */
	public List<Long> loadFollowedOfficialUserIds(){
		return template.queryForList(FOLLOWED_OFFICIAL_USER_QUERY, new Object[]{true},Long.class);
	}
}
